# -*- coding: utf-8 -*-
'''
Created on 2013-5-30
重出江湖数据包编码解码
@author: 不懂d叛逆
'''
# 命令编码
def encode(data):
	byte = list(data.encode("gbk"))
	byte.append(9)
	byte.append(10)
	keys = (0X0D, 0X4C, 0X16, 0X41, 0X01, 0X38, 0X4E, 0X0A, 0X57, 0X15, 0X4F, 0X1B, 0X4F, 0X06, 0X44, 0X00)
	i = 0
	j = 0
	flag = False
	for c in byte:
		if c != 32 and c != 10:
			if c == 9:
				flag = True
			else:
				c = c ^ keys[i]
				if c != 32 and c != 10 and c != 9 and c != 0:
					byte[j] = c
		j += 1
		i += 1
		if i >= 15 or flag == True:
			i = 0
			flag = False
	bs = bytes(byte)
	return bs

# 命令解码
class Decoder():
	def __init__(self):
		self.byte = []
		self.i = 0
		self.keys = (0X0D, 0X4C, 0X16, 0X41, 0X01, 0X38, 0X4E, 0X0A, 0X57, 0X15, 0X4F, 0X1B, 0X4F, 0X06, 0X44, 0X00)
		return
	def decode(self, data):
		self.byte+=list(data)
		data_len = len(self.byte)
		end = data_len
		for i in range(data_len - 1, 0, -1):
			if self.byte[i] == 9:
				end = i + 1
				break
		j = 0
		lastP = 0
		start = False
		result = []
		for c in self.byte:
			if j >= end:
				break
			key = self.__getKey(c)
			if key == 32:
				if c == 9 and start == True:
					self.byte[j] = 0
					piece = self.byte[lastP:j + 1]
					s = bytes(piece).decode('gbk', "ignore")
					result.append(s)
					lastP = j + 1
					start = False
			else:
				c = c ^ key
				if c != 32 and c != 10 and c != 9 and c != 0:
					self.byte[j] = c
					if start == False and c == 38:  # c==ord('&')
						start = True
						lastP = j
			j += 1
		self.byte = self.byte[end:data_len]
		return result
	def __getKey(self, c):
		if isinstance(c, int):
			if c == 9:
				self.i = 0;
				return 32
			elif c == 32 or c == 10:
				self.i += 1
				return 32
			else:
				self.i = self.i % 15
				r = self.keys[self.i]
				self.i += 1
				return r
		else:
			return 32

